package com.example.demo.controller;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.example.demo.config.PropertiesConfig;
import com.example.demo.service.AccessTokenService;
import com.google.gson.Gson;

@RestController
public class CodeImageController {

	protected final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	private PropertiesConfig propertiesConfig;

	@Autowired
	private AccessTokenService accessTokenService;

	@GetMapping("/generateCodeImage")
	public Object generateCodeImage(@RequestParam(value = "userId") String userId) {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("message", "操作成功");
		result.put("code", 20000);
		try {
			String urlQrcodeCreate = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token= {0}";
			String accessToken = accessTokenService.findById(propertiesConfig.getAppId()).get().getAccessToken();
			String url = MessageFormat.format(urlQrcodeCreate, accessToken);
			Map<String, Object> requestBodyMap = new HashMap<String, Object>();
			//TODO 二维码有效期
			requestBodyMap.put("expire_seconds", 120);//120
			requestBodyMap.put("action_name", "QR_STR_SCENE");
			Map<String, Object> sceneStrMap = new HashMap<String, Object>();
			sceneStrMap.put("scene_str", userId);//设置二维码场景值为userId，user表主键
			Map<String, Object> sceneMap = new HashMap<String, Object>();
			sceneMap.put("scene", sceneStrMap);
			requestBodyMap.put("action_info", sceneMap);
			String requestBody = new Gson().toJson(requestBodyMap);
			System.out.println("接口参数："+requestBody);
			Map<String, Object> apiResult = new HashMap<String, Object>();
			apiResult= restTemplate.postForObject(url, requestBody, Map.class);
//			apiResult.put("ticket", "gQGl7zwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyRnZTQWdiQjFmYjAxTUtYWXh1Y3QAAgS2OvxeAwR4AAAA");
			String ticket = (String)apiResult.get("ticket");
			System.out.println("微信二维码接口返回值："+apiResult);
			if(StringUtils.isEmpty(ticket)) {
				throw new Exception("微信二维码接口异常，"+apiResult);
			}
			String codeImageUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET";
			codeImageUrl = codeImageUrl.replace("TICKET", ticket);
			Map<String,String> data = new HashMap<String, String>();
			data.put("codeImageUrl", codeImageUrl);
			result.put("data", data);
		} catch (Exception e) {
			result.put("message", "操作失败，"+e.getMessage());
			result.put("code", 1);
		}
		return result;
//		正确
//		{
//		    "ticket": "gQHL7zwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyOE43QWd5QjFmYjAxUDg1WHh1Y1kAAgRQBfteAwR4AAAA",
//		    "expire_seconds": 120,
//		    "url": "http://weixin.qq.com/q/028N7AgyB1fb01P85XxucY"
//	    }
//		错误
//		{
//		    "errcode": 42001,
//		    "errmsg": "access_token expired hints: [IGadbpNre-Ik0ASa!]"
//		}
	}
}
